<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="auto"
      v-show="showSearch"
    >
      <el-row>
        <el-form-item label="生产单编码" prop="produceNo">
          <el-input
            v-model.trim="queryParams.produceNo"
            style="width: 180px"
            placeholder="请输入生产单编码"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="发货单编码" prop="code">
          <el-input
            v-model.trim="queryParams.code"
            style="width: 180px"
            placeholder="请输入发货单编码"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="书刊编码" prop="bookCode">
          <el-input
            v-model.trim="queryParams.bookCode"
            style="width: 180px"
            placeholder="请输入书刊编码"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="书刊名称" prop="bookName">
          <el-input
            v-model.trim="queryParams.bookName"
            style="width: 180px"
            placeholder="请输入书刊名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-row>
          <el-form-item label="发货月份" prop="yearMonth">
            <el-date-picker
              style="width: 180px"
              clearable
              v-model="queryParams.yearMonth"
              value-format="YYYY-MM"
              type="month"
              placeholder="请选择时间"
            />
          </el-form-item>
          <el-form-item label="发货日期" prop="deliveryDate">
            <el-date-picker
              style="width: 180px"
              clearable
              v-model="queryParams.deliveryDate"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="请选择时间"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              clearable
              placeholder="选择状态"
              style="width: 180px"
            >
              <el-option label="已提交" value="2"></el-option>
              <el-option label="未提交" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <div class="operation">
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </div>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>
    <div>
      <el-table
        v-loading="loading"
        border
        height="60vh"
        :data="dataList"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column label="序号" width="60" type="index" align="center" />
        <el-table-column
          label="状态"
          min-width="100"
          align="center"
          :show-overflow-tooltip="true"
          prop="status"
          v-if="columns[0].visible"
        >
          <template v-slot="{ row }">
            <dict-tag :options="ems_order_status" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column
          label="发货单编码"
          min-width="200"
          align="center"
          prop="code"
          v-if="columns[1].visible"
        >
          <template v-slot="{ row }">
            <el-button type="primary" @click="handleView(row)" text>{{
              row.code
            }}</el-button>
          </template>
        </el-table-column>
        <!--        <el-table-column-->
        <!--          label="生产单编码"-->
        <!--          min-width="200"-->
        <!--          align="center"-->
        <!--          prop="produceNo"-->
        <!--          v-if="columns[1].visible"-->
        <!--        >-->
        <!--        </el-table-column>-->

        <el-table-column
          label="生产单编码"
          min-width="200"
          align="center"
          :show-overflow-tooltip="true"
          prop="produceNo"
          v-if="columns[1].visible"
        >
          <template v-slot="{ row }">
            <div>
              <span
                v-for="(item, index) in row.produceNo?.split(',')"
                :key="index"
              >
                <el-button
                  type="primary"
                  @click="handleViewProduce(row, index)"
                  text
                  >{{ item }}</el-button
                >
                <br />
              </span>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="书刊编码"
          min-width="120"
          align="center"
          prop="bookCode"
          v-if="columns[2].visible"
        >
        </el-table-column>
        <el-table-column
          label="书刊名称"
          min-width="280"
          align="center"
          prop="bookName"
          v-if="columns[3].visible"
        >
        </el-table-column>
        <el-table-column
          label="发货日期"
          min-width="120"
          align="center"
          :show-overflow-tooltip="true"
          prop="deliveryDate"
          v-if="columns[4].visible"
        >
          <template v-slot="{ row }">
            {{ row.deliveryDate?.split("T")[0] ?? "" }}
          </template>
        </el-table-column>
        <el-table-column
          label="客户名称"
          min-width="120"
          align="center"
          prop="customName"
          v-if="columns[5].visible"
        >
        </el-table-column>
        <el-table-column
          label="发货数量"
          min-width="120"
          align="center"
          prop="quantity"
          v-if="columns[5].visible"
        >
        </el-table-column>
        <el-table-column
          label="累计发货量"
          min-width="120"
          align="center"
          prop="deliveryCount"
        >
          <template v-slot="{ row }">
            <div
              v-for="(item, index) in row.deliveryCount?.split(',')"
              :key="index"
            >
              {{ item }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="订单数量"
          min-width="120"
          align="center"
          prop="orderCount"
          v-if="columns[5].visible"
        >
        <template v-slot="{ row }">
            <div
              v-for="(item, index) in row.orderCount?.split(',')"
              :key="index"
            >
              {{ item }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="发货纸令数"
          min-width="120"
          align="center"
          prop="lingCount"
          v-if="columns[5].visible"
        >
        </el-table-column>
        <!-- <el-table-column
          label="印张 "
          min-width="120"
          align="center"
          prop="sheetCount"
          v-if="columns[5].visible"
        >
        </el-table-column> -->
     
        <!-- <el-table-column
          label="纸令数"
          min-width="120"
          align="center"
          prop="reamAmount"
          v-if="columns[5].visible"
        >
        </el-table-column> -->
        <el-table-column
          label="创建人"
          min-width="120"
          align="center"
          :show-overflow-tooltip="true"
          prop="createBy"
          v-if="columns[6].visible"
        >
        </el-table-column>
        <el-table-column
          label="创建日期"
          min-width="120"
          align="center"
          :show-overflow-tooltip="true"
          prop="createTime"
          v-if="columns[7].visible"
        >
          <template v-slot="{ row }">
            {{ row.createTime?.split("T")[0] ?? "" }}
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          min-width="120"
          align="center"
          :show-overflow-tooltip="true"
          prop="remark"
          v-if="columns[8].visible"
        >
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
          width="150"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <!-- <el-tooltip
              content="修改"
              placement="top"
              v-if="scope.row.status == 1"
            >
              <el-button
                link
                type="primary"
                icon="Edit"Shippingdetails
                @click="handleUpdate(scope.row)"
              ></el-button>
            </el-tooltip> -->
            <el-tooltip
              content="删除"
              placement="top"
              v-if="scope.row.status == 1"
            >
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-button
              link
              type="primary"
              v-if="scope.row.status == 1"
              @click="handleSubmit(scope.row)"
              >提交</el-button
            >
            <el-tooltip content="打印" placement="top">
              <el-button
                link
                type="primary"
                icon="Printer"
                @click="handlePrint(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <printView
      :visible="printOpen"
      @cancel="
        () => {
          printOpen = false;
          mainId = '';
        }
      "
      :id="mainId"
    ></printView>
  </div>
</template>

<script setup name="order">
// 编号改成序列号 纸张编号 印刷编号
import { toNumber } from "@/utils/ruoyi";
import { downLoadBlob } from "@/utils/ruoyi";
import printView from "./printview";
import {
  getDeliveryList,
  delDeliveryById,
  updateStatus,
  deliveryExport,
} from "@/api/production/invoice.js";
const { proxy } = getCurrentInstance();
const loading = ref(true);
const dataList = ref([]);
const showSearch = ref(true);
const total = ref(0);
const router = useRouter();
const mainId = ref("");
const printOpen = ref(false);
import { getToken } from "@/utils/auth";
// 列显隐信息
const columns = ref([
  { key: 0, label: `状态`, visible: true },
  { key: 1, label: `发货单编码`, visible: true },
  { key: 2, label: `书刊编码`, visible: true },
  { key: 3, label: `书刊名称`, visible: true },
  { key: 4, label: `发货日期`, visible: true },
  { key: 5, label: `客户名称`, visible: true },
  { key: 6, label: `创建人`, visible: true },
  { key: 7, label: `创建时间`, visible: true },
  { key: 8, label: `备注`, visible: true },
]);

const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  const fieldsToSum = ["status", "remark"];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    switch (column.property) {
      case "quantity":
        sums[index] = hashMap.value.quantity;
        break;
      case "orderCount":
        sums[index] = hashMap.value.orderCount;
        break;
      case "lingCount":
        sums[index] = hashMap.value.lingCount;
        break;
      default:
        break;
    }
    // if (!fieldsToSum.includes(column.property)) {
    //   const values = data.map((item) => Number(item[column.property]));
    //   if (!values.every((value) => isNaN(value))) {
    //     sums[index] = values.reduce((prev, curr) => {
    //       const value = Number(curr);
    //       if (!isNaN(value)) {
    //         return toNumber(prev + curr, 4);
    //       } else {
    //         return toNumber(prev, 4);
    //       }
    //     }, 0);
    //     sums[index];
    //   } else {
    //     sums[index] = "";
    //   }
    // }
  });

  return sums;
};

//   // 查看生产单明细
const handleViewProduce = (row, index) => {
  const produceId = row.produceId?.split(",")[index];
  const produceNo = row.produceNo?.split(",")[index];
  if (produceNo.indexOf("FM") > -1) {
    router.push({
      path: "/production/cover/coverDetails",
      query: {
        id: produceId,
        info: true,
        moduleCode: "invoice",
      },
    });
  } else {
    router.push({
      path: "/production/text/textDetails",
      query: {
        id: produceId,
        info: true,
        moduleCode: "invoice",
      },
    });
  }
};
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 50,
  },

  rules: {
    urgentDate: [
      { required: true, message: "加急交货日期不能为空", trigger: "blur" },
    ],
  },
});
const { queryParams } = toRefs(data);
//这里是打印的配置项
const { ems_order_status } = proxy.useDict("ems_order_status");

const getCurrentDay = () => {
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth() + 1; // 月份从0开始，需要加1
  var day = now.getDate();
  if (month < 10) {
    month = "0" + month;
  }
  if (day >= 0 && day <= 9) {
    day = "0" + day;
  }
  // queryParams.value.deliveryDate = year + "-" + month + "-" + day;
  queryParams.value.yearMonth = year + "-" + month;
};
const hashMap = ref({});
getCurrentDay();

const getList = () => {
  loading.value = true;
  getDeliveryList(queryParams.value)
    .then((res) => {
      loading.value = false;
      dataList.value = res.rows;
      if (res.rows.length > 0) {
        hashMap.value = res.rows[0].hashMap;
      }
      total.value = res.total;
    })
    .catch((err) => {
      loading.value = false;
    });
};
// 新增
const handleAdd = () => {
  router.push("/production/invoice/invoiceDetails");
};
// 编辑
const handleUpdate = (row) => {
  router.push({
    path: "/production/invoice/invoiceDetails",
    query: {
      id: row.id,
    },
  });
};
// 查看
const handleView = (row) => {
  router.push({
    path: "/production/invoice/invoiceDetails",
    query: {
      id: row.id,
      info: true,
    },
  });
};
// 打印
const handlePrint = (row) => {
  mainId.value = row.id;
  printOpen.value = true;
};

// 提交
const handleSubmit = (row) => {
  proxy.$modal
    .confirm('是否确认提交"' + row.code + '"的发货单？')
    .then(function () {
      return updateStatus({ status: 2, id: row.id });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("提交成功");
    })
    .catch(() => {});
};

// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryRef");
  handleQuery();
};
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除"' + row.code + '"发货单？')
    .then(function () {
      return delDeliveryById({ id: row.id });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
// 导出
const handleExport = () => {
  deliveryExport(queryParams.value).then((res) => {
    downLoadBlob(res, "发货单列表");
  });
};

getList();
// router.beforeEach((to, from, next) => {
//     if (to.path == "/basicInfo/personnel") {
//         getList()
//     }
//     next();
// });
</script>

<style lang="scss" scoped>
.operation {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 18px;
}
</style>
